<template>
	<div class="xgrid" ref="xgridRef">
		<vxe-grid
			ref="JGridRef"
			size="mini"
			border
			resizable
			highlight-hover-column
			highlight-current-column
			highlight-current-row
			highlight-hover-row
			transfer
			show-overflow
			footer-cell-class-name="footerCellClassName"
			:row-id="tbId"
			:style="{ width: gridWidth ? gridWidth + 'px' : 'auto' }"
			:tree-config="treeConfig"
			:cell-class-name="cellClass"
			:show-footer="showFoot"
			:height="hei"
			:columns="columns"
			:data="lists"
			:menu-config="tableMenu"
			:checkbox-config="{ checkField: 'checked', strict: true }"
			:footer-method="footerMethod"
			:print-config="{ sheetName: '表格打印' }"
			:loading="load.loading"
			:row-class-name="rowClassName"
			:sort-config="{ multiple: true, trigger: 'cell', remote: remoteSort }"
			:export-config="{}"
			:edit-config="{ trigger: 'click', mode: 'cell', enabled: true }"
			@editClosed="editClosed"
			:pager-config="{
				enabled: sp,
				layouts: layout,
				pageSize: pageSize,
				currentPage: currentPage,
				total: total,
				pageSizes: pageSizes,
				align: 'left',
				perfect: false,
			}"
			@page-change="handlePageChange"
			@checkbox-change="checkboxChange"
			@sort-change="sortChange"
			@checkbox-all="checkboxAll"
			@cell-dblclick="cellDblClick"
			@cell-click="cellClick"
			@filter-visible="filterVisible"
		>
			<template #op="{ row }">
				<div v-if="columns[columns.length - 1].btns" style="padding-left: 5px">
					<template v-for="(btn, btnIndex) in columns[columns.length - 1].btns" :key="btnIndex">
						<span class="btn" v-if="showBtn(row, btn)" @click="rowBtn(btn, row)">
							{{ btn.label }}
						</span>
					</template>
				</div>
			</template>
			<template #empty>
				<el-empty description="无数据" />
			</template>
		</vxe-grid>
		<JDialog ref="JEditorRef" />
	</div>
</template>
<script>
import tool from '@/utils/tool';
import '@/utils/VxeTable';
import JDialog from '@/lui/JEditor.vue';
export default {
	name: 'JGrid',
	components: { JDialog },
	props: {
		seq: { type: Boolean, default: false }, // 显示表格底部
		card: { type: Boolean, default: true }, // 显示表格底部
		showFooter: { type: Boolean, default: true }, // 显示表格底部
		showPage: { type: Boolean, default: true }, // 显示表格底部
		openPage: { type: Boolean, default: true }, // 是否打开窗口
		showCheckRow: { type: Boolean, default: true }, // 显示复选框列
		showNumRow: { type: Boolean, default: true }, // 显示行号列
		editable: { type: Boolean, default: false },
		loading: { type: Boolean, default: false },
		autoLoad: { type: Boolean, default: true }, // 显示表格底部
		isTree: { type: Boolean, default: false }, // 树形表格
		remoteSort: { type: Boolean, default: true }, // 树形表格
    dbClickEdit: { type: Boolean, default: false }, // 双击编辑
		detail: { type: Boolean, default: false }, // 取明细表列配置
		fileName: { type: String, default: '' }, // 下载的文件名
		gridHeight: { type: [Number, String], default: 0 }, // 下载的文件名
		gridWidth: { type: Number, default: 0 }, // 下载的文件名
		offsetHeight: { type: [Number, String], default: 0 }, // 减去高度
		size: { type: String, default: 'mini' }, //
		whichPage: { type: String, default: '' }, //
		header: { type: String, default: '' }, //
		listUrl: { type: String, default: '' }, //
		top: { type: Number, default: 0 }, //
		contextmenu: {
			type: Array,
			default: function () {
				return [];
			},
		}, // 表格右键菜单
		fields: {
			type: Array,
			default: function () {
				return [];
			},
		}, // 表格右键菜单
		dataList: {
			type: Array,
			default: function () {
				return [];
			},
		}, // 表格右键菜单
		searchModel: {
			type: Object,
			default: function () {
				return {};
			},
		}, // 搜索条件
	},
	data() {
		return {
			url: '',
			filterColumns: [
				{ field: '', type: 'seq', width: 40, align: 'center', visible: true },
				{ field: 'checked', type: 'checkbox', width: 40, align: 'center', visible: true },
				{ field: 'val', title: '值', width: 160, align: 'left', visible: true },
			],
			filterList: [],
			exportConfig: {
				filename: this.fileName,
				mode: 'all',
				original: false,
				remote: this.exportRemote,
				exportMethod: () => {
					this.getList(true);
				},
				columnFilterMethod: this.exportFilterMethod,
			}, // 导出配置
			fieldObj: {},
			pageSize: 200,
			currentPage: 1,
			list: [],
			total: 0,
			fApi: null,
			columns: [],
			hei: this.gridHeight,
			load: {
				loading: false,
			},
			filterOpen: false,
			hideFooter: false,
			hidePage: false,
      query: {},
      timeval: 0
		};
	},
	emits: ['rowBtn', 'mounted', 'cellClick', 'cellDblClick', 'editClosed'],
	methods: {
		setApi(api) {
			this.fApi = api;
		},
    openEdit ( pars ) {
      this.$refs.JEditorRef.open({ title: pars.title, params: pars })
    },
    getList(excel = 0) {
      if (!this.url) return;
      let search = {
        ...this.query
      }
      if (this.fApi) {
        if (this.fApi.getValue('search')) {
          search = Object.assign(search, this.fApi.getValue('search'));
        }
        if (this.fApi.getValue('toolbar')) {
          search = Object.assign(search, this.fApi.getValue('toolbar'));
        }
      }
      else {
        search = Object.assign(search, this.searchModel);
      }
      let params = {
        excel,
        whichPage: this.whichPage,
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        formData: search,
        sort: this.getSort(),
      };
      this.load.loading = true;
      tool.post(this.url, params, this.load).then((ret) => {
        if (ret.stat) {
          if (excel && ret.data) {
            window.open(ret.data, '_blank');
          } else {
            this.total = ret.data.total;
            if (this.fApi) {
              if (this.fApi.getValue('toolbar')) {
                this.fApi.exec('toolbar', 'updateTotal', this.total);
              }
            }
            ret.data.list.map((row) => {
              row.checked = false;
            });
            if(ret.data.columns) {
              this.columns = ret.data.columns
            }
            this.list = ret.data.list;
          }
        }
      });
    },
		filterVisible({ visible }) {
			if (this.filterOpen === visible) {
				this.$refs.JGridRef.closeFilter();
			} else {
				this.filterOpen = visible;
			}
		},
		rowBtn(btn, row) {
			if (typeof btn.click === 'function') {
				btn.click(row);
			} else {
				this.$emit('rowBtn', btn, row);
			}
		},
		// 设置表格高度
		setGridHeight() {
			if (!this.gridHeight) {
				setTimeout(() => {
					let rect = this.$refs.xgridRef.getBoundingClientRect();
					let h = tool.xe.toInteger(window.innerHeight - rect.top) - 0;
					if (this.offsetHeight) {
						if (typeof this.offsetHeight === 'string') {
							h = tool.multiply(h, this.offsetHeight);
						}
						if (typeof this.offsetHeight === 'number') {
							h = h - this.offsetHeight;
						}
					}
					this.hei = h;
					this.$emit('mounted');
				}, 300);
			}
		},
		// 设置列
		getGridColumns() {
			if (this.columns.length === 0) {
				tool.post('page/getGridColumns', { whichPage: this.whichPage, detail: this.detail }).then((ret) => {
					if (ret.stat) {
						this.hideFooter = ret.data.hideFooter;
						this.hidePage = ret.data.hidePage;
						if (this.detail) {
							this.columns = ret.data.detailGrid;
						} else {
							let columns = new Function('_this', '_tool', 'return' + ret.data.fields)(this, tool);
							this.columns = columns;
							if (ret.data.listUrl) {
								this.url = ret.data.listUrl ? ret.data.listUrl : 'list/bill';
								setTimeout(() => {
                  this.getList();
                }, 300)
							}
						}
					}
				});
			}
      else {
        if(this.listUrl) {
          this.url = this.listUrl
          this.getList();
        }
      }
		},
		showBtn(row, btn) {
			if (typeof btn.show === 'undefined') return true;
			return new Function('row', 'return ' + btn.show)(row);
		},
		search() {
			this.currentPage = 1;
			this.getList();
		},
		// 工具栏分页
		toobarPageChange({ currentPage, pageSize }) {
			this.currentPage = currentPage;
			this.pageSize = pageSize;
			this.getList();
		},
		getSort() {
      if(!this.remoteSort) return
			let list = [];
			let sort = this.$refs.JGridRef.getSortColumns();
			sort.map((row) => {
				list.push({
					field: row.field,
					order: row.order,
				});
			});
			return list;
		},
		editClosed({ row, column }) {
			this.$emit('editClosed', row, column);
		},
		handlePageChange({ type, pageSize }) {
			if (type === 'size') {
				this.currentPage = 1;
			}
			this.pageSize = pageSize;
			this.getList();
		},
		refresh() {
			this.currentPage = 1;
			this.getList();
		},
		sortChange() {
			if (!this.remoteSort) return;
			this.getList();
		},
		checkboxChange() {
			this.updateFooter();
		},
		rowClassName({ row }) {
			let css = '';
			if (row.billType === '小计' || row.amount === '小计') {
				css += 'row-green';
			}
			if (row.transTypeName && row.transTypeName === '小计') {
				css += ' subTotal ';
			}
			return css;
		},
		setData(total, data) {
			this.total = total;
			this.lists = data;
			this.$refs.JGridRef.reloadData(data);
		},
		getOffset() {
			return this.$refs.xgridRef.getBoundingClientRect();
		},
		updateFooter() {
			this.$refs.JGridRef.updateFooter();
		},
		// 全选
		checkboxAll() {
			this.updateFooter();
		},
		// 底部汇总
		footerMethod({ columns, data }) {
			let ret = [];
			let list = data.filter((row) => {
				return row.checked;
			});
			if (list.length === 0) list = data;
			let cols = [];
			this.columns.map((row) => {
				if (row.children) {
					row.children.map((col) => {
						cols.push(col);
					});
				} else {
					cols.push(row);
				}
			});
			ret = columns.map((column) => {
				let col = {};
				for (let i = 0; i < cols.length; i++) {
					if (cols[i].field === column.property) {
						col = cols[i];
					}
				}
				if (col.sum === true) {
					if (column.property === 'assQty') {
						// 汇总选中的辅助数量，只汇总 规格，单位一样的
						let crows = data.filter((row) => {
							return row.checked;
						});
						if (crows.length === 0) return '';
						let sumRows = [];
						let q = [];
						if (crows.length > 0) {
							let c1 = crows[0];
							for (let i = 0; i < crows.length; i++) {
								let r = tool.xe.clone(crows[i]);
								if (c1.spec !== r.spec) {
									return tool.err('不同规格的商品不能汇总');
								}
								r.retailQty = -tool.xe.toNumber(r.retailQty);
								sumRows.push(r);
								q.push(r.retailQty);
							}
						}
						let u1 = sumRows[0].unit1;
						let u2 = sumRows[0].unit2;
						let spec = sumRows[0].spec;
						let qty = tool.xe.sum(sumRows, 'retailQty');
						//
						let q1 = (qty - (qty % spec)) / spec;
						let q2 = qty % spec;
						let units = '';
						if (q1) {
							units += q1 + u1;
						}
						if (q2) {
							units += q2 + u2;
						}
						return units;
					} else {
						let s = tool.xe.sum(list, column.property);
						if (s) {
							if (column.formatter === 'formatMoney') {
								s = s ? tool.xe.toFixed(s, 2) : '';
							}
							return s;
						} else {
							return '';
						}
					}
				}
				if (typeof col.sumIsLast !== 'undefined' && col.sumIsLast) {
					if (data.length - 1 >= 0) return tool.xe.toFixed(data[data.length - 1][column.property], 2);
				}

				if (typeof col.subSum !== 'undefined' && col.subSum) {
					let subList = list.filter((row) => {
						return row.transTypeName === '小计';
					});
					let s = tool.xe.sum(subList, column.property);
					if (s) {
						if (column.formatter === 'formatMoney') {
							s = s ? tool.xe.toFixed(s, 2) : '';
						}
						return s;
					} else {
						return '';
					}
				}
				return '';
			});
			return [ret];
		},
		// cell样式名
		cellClass({ row, column }) {
			let field = column.field;
			let css = ' ';
			if (field && field === 'billStateName') {
				if (row.billState) css += ' billState-' + row.billState;
			}
			if (field && field === 'seq') {
				css += ' seq ';
			}
			if (
				field &&
				typeof this.colObject[field] !== 'undefined' &&
				typeof this.colObject[field].canClick !== 'undefined' &&
				this.colObject[field].canClick
			) {
				css += ' canClick ';
			}
			if (row[field] === '小计') {
				css += ' subTotal ';
			}
			return css;
		},
		// 双击单元格
		cellDblClick({ row, column }) {
      if(this.dbClickEdit) {
        if(this.columns && this.columns.length > 0) {
          let opCol = this.columns[this.columns.length-1]
          if(opCol.btns && opCol.btns.length > 0) {
            for (let i = 0; i < opCol.btns.length; i++) {
              if(opCol.btns[i].label === '编辑') {
                if(typeof  opCol.btns[i].click === 'function')
                  opCol.btns[i].click(row)
                break
              }
            }
          }
        }
      }
			this.$emit('cellDblClick', { row, column });
		},
		// 单击单元格
		cellClick({ row, column }) {
			let field = column.property;
			let cols = this.columns.filter((row) => {
				return field === row.field;
			});
			if (cols.length === 1) {
				let col = cols[0];
				if (row[column.field] === '小计') return;
				if (row[column.field] && col.canClick ) {
          tool.openPage(row, field, this.$route, this.$router);
				}
        else {
          this.$emit('cellClick', { row, column });
        }
			}
			if (field && field === 'checked') {
				return this.updateFooter();
			}
		},
		// 打印当前页面
		toPrint() {
			this.$refs.JGridRef.openPrint({ sheetName: this.fileName });
		},
		download() {
			this.$refs.JGridRef.openExport();
		},
	},
  created() {
    if(this.$route.query && !tool.xe.isEmpty(this.$route.query)) {
      let que = this.$route.query
      delete que.m
      this.query = que
      if(!tool.xe.isEmpty(que)) {
        // setTimeout(() => {
        //   this.fApi.exec('search', 'setData', que)
        //   // this.query = {}
        // }, 200)
      }
    }
    this.hei = this.gridHeight ? this.gridHeight : 300;
    if (this.listUrl) this.url = this.listUrl;
    if (this.fields && this.fields.length > 0) {
      this.columns = this.fields;
    }
    if (this.dataList && this.dataList.length > 0) {
      this.list = this.dataList;
    }

    if (this.whichPage) {
      this.getGridColumns();
    }
    window.addEventListener('resize', this.setGridHeight);
  },
  activated() {
    this.getList();
    window.addEventListener('resize', this.setGridHeight);
  },
  deactivated() {
    window.removeEventListener('resize', this.setGridHeight);
  },
  computed: {
    showFoot() {
      return this.showFooter && !this.hideFooter;
    },
    // 显示页码
    sp() {
      return this.showPage && !this.hidePage;
    },
    layout() {
      return ['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total'];
    },
    // 右键菜单
    tableMenu() {
      let menu = {
        header: {
          options: [
            [
              { code: 'hideColumn', name: '隐藏列', disabled: false },
              { code: 'showAllColumn', name: '取消所有隐藏列', disabled: false },
            ],
          ],
        },
        body: {
          options: [this.contextmenu],
        },
      };
      if (this.contextmenu.length === 0) return {};
      return menu;
    },
    // 选中行
    checkedRows() {
      return this.list.filter((row) => {
        return row.checked;
      });
    },
    // 筛选选中的行
    filterCheckedRows() {
      return this.filterList.map((row) => {
        return row.id;
      });
    },
    treeConfig() {
      return this.isTree ? { children: 'children', expandAll: false } : null;
    },
    tbId() {
      return 'JGrid' + Date.now();
    },
    colObject() {
      let obj = {};
      for (let i = 0; i < this.columns.length; i++) {
        obj[this.columns[i].field] = this.columns[i];
      }
      return obj;
    },
    pageSizes() {
      return [200, 500, 2000, 10000];
    },
    lists: {
      get() {
        return this.list;
      },
      set() {},
    },
  },
  watch: {
    dataList: {
      handler: function (val) {
        this.list = val;
      },
      deep: true,
    },
    fields: {
      deep: true,
      handler: function (val) {
        this.columns = val;
      },
    },
  },
  mounted() {
    this.setGridHeight();
  },
}
</script>

<style scoped lang="scss">
.xgrid {
	width: 100%;
	box-sizing: border-box;
	padding: 0 5px;
	background-color: white;
	margin-bottom: 3px;
}
.btn {
	color: #01aaee;
	font-size: 12px;
	margin-right: 8px;
}
//vxe-body--column col_26 col--seq col--ellipsis
:deep(.col--seq) {
  //background-color: #CCD1D9;
}
.btn {
	&:hover {
		cursor: pointer;
		color: #2b85e4;
	}
}
:deep(.subTotal) {
	font-weight: bold;
	//background-color:#e2e2e2;
	font-size: 13px;
}
.vxe-body--row.row-green {
	background-color: lighten(#4fc1e9, 10%) !important;
	color: white;
}

:deep(.vxe-cell) {
	padding: 0 2px !important;
}
:deep(.billState-draft) {
	color: mediumseagreen;
	//background-color: lightyellow;
	&.billNo {
		color: dodgerblue;
	}
}

:deep(.billState-del) {
	color: #bdbdbd;
	&.billNo {
		color: dodgerblue;
	}
}

:deep(.vxe-table--render-default.vxe-editable.size--mini .vxe-body--column) {
	//height: 30px !important;
}
:deep(.footerCellClassName) {
	font-size: 12px;
	height: 35px;
	padding: 0 !important;
	color: #f56c6c;
}
:deep(.canClick) {
	color: dodgerblue;
	cursor: pointer;
	&:hover {
		text-decoration: underline;
	}
}
</style>